<?php
/**
 * Auth
 */
class controller_auth extends controller_base {

	/**
	 * 登录表单
	 */
	public function action_login() {
		//登录前的URL
		$referer = empty($_GET['referer']) ? '' : $_GET['referer'];
		$this->assign('referer', $referer);
	}
	
	/**
	 * 登录 do
	 */
	public function action_login_do() {
        $var = new model_var();

        //收发邮件人
        $mail_from = array();
        parse_str(str_replace("\r\n", '&', Config::get('MAIL_FOR_BACKUP_FROM_INFO')), $mail_from);

        $failedTimesVar = $var->get('login_failed_times');
        $failedTimes = explode(',', $failedTimesVar);
        $date = isset($failedTimes[0]) ? $failedTimes[0] : '';
        $num = isset($failedTimes[1]) ? intval($failedTimes[1]) : 0;

        if ($date !== date('Ymd'))
        {
            $num = 0;
        }

        //大于3次拒绝登录
        if ($num >= 3)
        {
            sleep(5);

            new model_logs('Login Denied / '.$_SERVER['HTTP_USER_AGENT']);

            //发送邮件
            $smtp = new common_smtp($mail_from['smtp'], 25, true, $mail_from['fullname'], $mail_from['password']);
            @$smtp->sendmail('qroom@qq.com', $mail_from['fullname'], '[FMS]登录失败次数过多', print_r($_SERVER, 1), 'TEXT');

            exit('Login Denied!');
        }

		if(empty($_POST['password']))
        {
			$this->message('密码不能为空', '?m=auth&a=login');
		}
		
        //验证
		$password = implode('', $_POST['password']);
		
		$model_auth = new model_auth();
        $ret = $model_auth->login($password);
		
		if ($ret)
        {
			new model_logs('Login Success / '.$_SERVER['HTTP_USER_AGENT']);

			$url = empty($_POST['referer']) ? './' : base64_decode($_POST['referer']);
			
			$this->message('登录成功', $url);
		}
        else
        {
			new model_logs('Login Fail / '.$password.' / '.$_SERVER['HTTP_USER_AGENT']);

            //计数器
            $num++;
            $var->set('login_failed_times', date('Ymd,').$num);

            //发送邮件
            $smtp = new common_smtp($mail_from['smtp'], 25, true, $mail_from['fullname'], $mail_from['password']);
            @$smtp->sendmail('qroom@qq.com', $mail_from['fullname'], '[FMS]登录失败', print_r($_SERVER, 1), 'TEXT');

			//发送飞信提醒
			$model_fetion = new model_fetion();
			$model_fetion->send('登录失败!当天第'.$num.'次, IP:'.$_SERVER['REMOTE_ADDR'].', 时间'.date('Y-m-d H:i:s'));
			
			$this->message('登录失败', '?m=auth&a=login');
		}

	}
	
	/**
	 * 退出
	 */
	public function action_logout() {
		$model_auth = new model_auth();
		$model_auth->logout();
		echo '<script>parent.location.href="./"</script>';
		exit;
	}

}
